import { getComponentById, useComponentsStore } from "@/stores/edit-pages-store";
import { LowCodePageContext, PropertiesTreeNode } from '@/pages/lowCodeEditorPlus/contextProvider/LowCodePageProvider';
import { useContext, useEffect, useRef, useState } from "react";
import { DownOutlined } from '@ant-design/icons';
import { Switch, Tree } from 'antd';
import type { TreeProps, GetRef } from 'antd';
import { cloneDeep } from "lodash-es";

type TreeRef = GetRef<typeof Tree>
export function VariableTree({insertVariable}:{insertVariable: (variable: string) => void}){
  const { schema, curComponent, curComponentId } = useComponentsStore();
  const { contextProperties } = useContext(LowCodePageContext);
  const [treeData, setTreeData] = useState<PropertiesTreeNode[]>([]);
  const treeRef = useRef<TreeRef>(null);
  useEffect(() => {
    const tempData = [{
      title: '组件上下文',
      key: 'component_context',
      children: getContextData(),
      disabled: true
    }]
    setTreeData(tempData)
  }, [])
  function getContextData(){
    if(!curComponent)return []
    
    let index = 0
    const arr: PropertiesTreeNode[] = []
    const curData = cloneDeep(contextProperties[curComponent.id])
    if(curData){
      curData.title= `当前层(${curData.title})`
      arr.push(curData)
    }
    
    const {parentId} = curComponent;
    function loopExe(parentId: string| undefined){
      if(!parentId)return
      const component = getComponentById(parentId, schema);
      if(component){
        const pData = cloneDeep(contextProperties[component?.id])
        if(pData){
          const prefix = `上${index+1}层`
          pData.title= `${prefix}(${pData.title})`
          arr.push(pData)

          loopExe(pData.parentId)
        }
      }
      return
    }
    loopExe(parentId)
    return arr
  }

  const onSelect: TreeProps['onSelect'] = (selectedKeys, info) => {
    if(selectedKeys.length>0){
      const val = `$\{${selectedKeys[0]}}`
      insertVariable(val)
    }
  };

  function handleSwitch(checked: boolean){
    if(checked){
      const arr: React.Key[] = []
      function loopFn(treeArr: PropertiesTreeNode[]){
        treeArr.forEach(item=>{
          if(item.children){
            arr.push(item.key)
            loopFn(item.children)
          }
        })
      }
      loopFn(treeData)
      treeRef?.current?.setExpandedKeys(arr)
    }else{
      treeRef?.current?.setExpandedKeys([])
    }
  }
  return (
    <section>
      <h3 className="columnTitle">
        <span>变量</span>
        <div><span>展开全部</span> <Switch size="small" onChange={handleSwitch}/></div>
      </h3>
      <Tree
        ref={treeRef}
        showLine
        switcherIcon={<DownOutlined />}
        selectedKeys={[]}
        onSelect={onSelect}
        treeData={treeData}
      />
    </section>
  )
}